/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
/*
   // 判断是否存在环，存在返回快慢指针相遇节点；不存在返回nullptr
    ListNode* hasCycle(ListNode *head) {
        ListNode* fast = head, *slow = head;
        while(fast != nullptr && fast->next != nullptr){
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow)
                return fast;
        }
        return nullptr;
    }

    ListNode *detectCycle(ListNode *head) {
        ListNode* cur = hasCycle(head);
        if(cur == nullptr) return nullptr;
        ListNode* cur1 = head;
        while(cur1 != cur){
            cur1 = cur1->next;
            cur = cur->next;
        }
        // 相遇节点为环入口
        return cur;
    }
*/
    ListNode *detectCycle(ListNode *head) {
        ListNode* fast = head, *slow = head;
        ListNode* cur = head;
        while(fast != nullptr && fast->next != nullptr){
            fast = fast->next->next;
            slow = slow->next;
            // 快慢指针相遇，此时从head 和 相遇点，同时查找直至相遇
            if(fast == slow){
                while(fast != cur){
                    fast = fast->next;
                    cur = cur->next;
                }
                // 相遇节点为环入口
                return cur;
            }
        }
        
        return nullptr;
    }
};